#!/usr/bin/python
# -*- coding:utf-8 -*-   
#encoding=utf-8
#author=daimin

import os
import conf

import datetime
import logging
import time
import hashlib
import binascii
import struct
import socket
import cPickle

def isNotEmpty(text):
    if text:
        return True
    return text.isspace()
    return False


logger = None

def getlogger(logfile = None):
    """获取日志对象
    """
    global logger
    if logger == None:
        logger = logging.getLogger() 
        if logfile == None:
            logfile = os.path.join(conf.self_log_dir, datetime.datetime.now().strftime("%Y%m%d") + ".log")
        else:
            logfile = os.path.join(conf.self_log_dir, logfile)
        
        hdlr = logging.FileHandler(logfile)
        formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
        hdlr.setFormatter(formatter)
        hdlr.setLevel(logging.INFO)
        logger.addHandler(hdlr)
        
        ch = logging.StreamHandler()
        ch.setFormatter(formatter)
        ch.setLevel(logging.DEBUG)
        logger.addHandler(ch)
        
        logger.setLevel(logging.NOTSET)
       
        logger.debug("initialize logger")
    
    return logger
      
    
    
'''
检验一个变量是否存在
'''
def  isset(v):
    try:
        type (eval(v))
    except:
        return   0
    else:
        return   1    

def empty(s):
    """判断指定的值是否是空 
    """
    if s == None:
        return True
    if s == False:
        return True
    if  isinstance(s,str) or isinstance(s,unicode):
        s = s.strip()
        if s == '':
            return True
    elif isinstance(s,int) or isinstance(s,float):
        if s == 0:
            return True
    elif isinstance(s, list) or isinstance(s, dict) or isinstance(s, tuple):
        if len(s) <= 0:
            return True
        
    return False


def utf82gbk(tstr):
    """转换UTF-8格式的编码为GBK编码
    """
    return tstr.decode("UTF-8").encode("GBK")
    
def datetime2timestamp(dt):
    return time.mktime(dt.timetuple())

def datetime2timestamp2(dt):
    """将datetime转换成日期秒数的方式
    """
    ndt = datetime.datetime(year=dt.year, month=dt.month, day=dt.day)
    return int(time.mktime(ndt.timetuple()))

def timestamp2datetime(ts):
    return datetime.datetime.fromtimestamp(ts)


def escSlash(s):
    return s.replace('\\','\\\\')    

def spechar(s):
    return s.replace("'", "\'")

def usd2rmb(uds):
    return int((uds+0.1) * 6)
    
def dict2param(d):
    if not isinstance(d, dict):
        return ''
    params = []
    for (key, val) in d.items():
        params.append("%s=%s" %(key, val))
        
    return "&".join(params)

def get_available_mem_size():
    '''得到系统可用内存大小
    '''
    import psutil 
    import platform
    is_linux = True if "Linux" in platform.system() else False
    available = 0
    try:
        if not is_linux:
            (_, available, _, _, _) =  psutil.virtual_memory()
        else:
            (_, available, _, _, _,_,_,_,_) =  psutil.virtual_memory()
    except:
        pass
    return  available

def md5(src, t='lower'):
    if t is 'lower':
        return hashlib.md5(src).hexdigest().lower()
    else:
        return hashlib.md5(src).hexdigest().upper()
    
def deco_log(t):
    """日志记录装饰器
    """
    def _deco_log(func):
        def __deco_log(**kwargs):
            if t in kwargs:
                getlogger().info(kwargs[t])
            return func(**kwargs)
        return __deco_log
    return _deco_log

def ef_hash(src, factor=1):
    return binascii.crc32(src * factor) ^ 0xFFFFFFFF

def load_cfg(func):
    import ConfigParser
    config = ConfigParser.ConfigParser()
    try:
        config.read(conf.ini_config_file)
        for se in config.sections():
            conf.G_CFG[se] = dict(config.items(se))
    except:
        print ('ini config file load fail!!!')
        raise Exception('ini config file load fail!!!')
    
    return func

def get_day_search_time(day):
    tomday = day + datetime.timedelta(days = 1 )
    return (int(datetime2timestamp(datetime.datetime(day.year, day.month, day.day))),\
            int(datetime2timestamp(datetime.datetime(tomday.year, tomday.month, tomday.day))))

def ip2long(ipstr):
    if ipstr is None or ipstr == '' or ipstr == 'null': return 0
    return struct.unpack("!I", socket.inet_aton(ipstr))[0]

    
def decompression(fpath):
    exts =  os.path.splitext(fpath)
    if exts is None or len(exts) < 2 or exts[1].upper() != '.GZ':
        return fpath
    logdir = os.path.dirname(fpath)
    ## 检查下解压后的文件是否已经存在
    ftarlog = '%s.log' % (exts[0])
    if os.path.exists(ftarlog) : return None
    if os.system('tar xvf %s -C %s' % (fpath, logdir)) == 0:
        return ftarlog
    else:
        return None
    
def serialize(val):
    try:
        return cPickle.dumps(val)
    except:
        return None

def unserialize(val):
    try:
        return cPickle.loads(val)
    except:
        return None
    
    
    
